import config from '../../config'
const API = config.api
const app = getApp();
import {
  checkLicense
} from '../../utils/util'
// var QQMapWX = require('../../utils/qqmap-wx-jssdk/qqmap-wx-jssdk.js');
// var qqmapsdk;
Page({
  data: {
    // StatusBar: app.globalData.StatusBar,
    // CustomBar: app.globalData.CustomBar,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    isAuthorizeGetUserInfo: false,
    isLogin: false,
    isMask: false,
    isShowCode: false,
    swiperInfo: [],
    radio: false,
    indexVideo: '',
    userId: '',
    modleshow: false,
    applylist: "",
    nation: "",
    province: '',
    city: '',
    district: "",
    address: "",
    latitude: '',
    longitude: '',
    customerserviceshow: false,
    customer: ""
  },

  phoneOn() {
    wx.makePhoneCall({
      phoneNumber: '400-830-8999' //仅为示例，并非真实的电话号码
    })
  },
  phoneOn2() {
    wx.makePhoneCall({
      phoneNumber: '800-830-8999' //仅为示例，并非真实的电话号码
    })
  },
  onLoad(query) {
    // console.log(query.customer);
    if (query.customer) {
      this.setData({
        customer: query.customer
      })
    }
    const q = decodeURIComponent(query) // 获取到二维码原始链接内容
    console.log(q);
    // qqmapsdk = new QQMapWX({
    //     key: '5XKBZ-QMOLI-O2YGU-UTL65-GUZFK-V7BLN' //这里自己的key秘钥进行填充
    // });
    this.setData({
      modleshow: true
    })
    console.log(checkLicense('91440300MA5FAY4Q5C'))
    app.getDeviceSize().then(res => {
      const {
        bottomLift,
        windowHeight,
        statusBarHeight,
        CustomBar
      } = res
      this.setData({
        bottomLift,
        windowHeight,
        statusBarHeight,
        CustomBar
      })
    })
    let userId = wx.getStorageSync('userId') || '';
    if (userId != '') return;
    this.getCode()

  },
  closebtnfn() {
    this.setData({
      modleshow: false,
      customerserviceshow:true
    })
    this.getUserLocation()
  },
  toagreement() {
    wx.navigateTo({
      url: '/pages/agreement/agreement'
    })
  },
  changeRadio() {
    this.setData({
      radio: !this.data.radio
    })
  },
  getCode() {
    wx.login({
      // 发送 res.code 到后台换取 openId, sessionKey, unionId
      success: loginRes => {
        console.log(loginRes)
        this.setData({
          code: loginRes.code
        })
      }
    })
  },
  apply() {
    console.log(!this.data.userId);
    if (!this.data.userId) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
      // this.setData({
      //   isLogin: true,
      //   isMask: true
      // })
    } else {
      app.http(API.apiGetState, {
        userId: this.data.userId
      }).then(res => {
        console.log(res);
        if (res.code == 200) {
          let rspData = JSON.parse(res.rspData);
          console.log(rspData);
          this.setData({
            applylist: rspData
          })
          // console.log(this.data.applylist);
          var etcInfo = !rspData.jsonData || rspData.jsonData == '' ? '' : JSON.parse(rspData.jsonData)

          if (rspData.state == 0) {
            wx.navigateTo({
              url: '/pages/addIDcard/addIDcard'
            });
          } else if (rspData.state == 1) {
            wx.navigateTo({
              url: '/pages/drivingLicense/drivingLicense'
            });
          } else if (rspData.state == 2) {
            wx.navigateTo({
              url: '/pages/drivingLicense/drivingLicense'
            });
          } else if (rspData.state == 3) {
            if (etcInfo.submitOrderStatus == 1) {
              wx.navigateTo({
                url: '/pages/biddingBank/biddingBank?etcInfo=' + JSON.stringify(etcInfo)
              });
            } else {
              this.setData({
                etcInfo
              })
              this.productDetail()
            }

          } else if (rspData.state == 4) {
            wx.navigateTo({
              url: '/pages/submit_success/submit_success'
            });
          }
          console.log(rspData)
        } else {
          wx.navigateTo({
            url: `/pages/apply/apply?customer=${this.data.customer}`
          });
        }

      })

    }
    let token = wx.getStorageSync('token');
    // if(token!==""){
    //     this.getposition()
    // }
  },
  //产品推荐查询
  productDetail() {
    wx.showLoading({
      title: '提交资料中...',
      mask: true
    })
    app.http(API.apiProductDetail, {
      userId: this.data.userId,
      bind_tel: this.data.etcInfo.saveAccountInfoRequest.mobilephone,
      idtype: this.data.etcInfo.saveAccountInfoRequest.idtype,
      approved_count: this.data.etcInfo.saveCarInfoRequest.approved_count,
      vehicle_length: this.data.etcInfo.saveCarInfoRequest.vehicle_length,
      vehicle_plate: this.data.etcInfo.saveCarInfoRequest.vehicle_plate,
      vehicle_color: this.data.etcInfo.saveCarInfoRequest.vehicle_color,
      vehicle_axles: this.data.etcInfo.saveCarInfoRequest.vehicle_axles,
      total_mass: this.data.etcInfo.saveCarInfoRequest.total_mass,
      car_type: 0,
      productId: '02',
      user_type: 8,
    }).then(res => {
      if (res.code == 200) {
        this.submitOrder();
      } else {
        wx.showModal({
          title: '提示',
          content: res.message,
          confirmColor: '#005866',
          showCancel: false,
          success(res) {}
        })
      }
    }).catch(err => {
      wx.showToast({
        title: '请求超时',
        icon: 'none',
        duration: 3000,
        mask: false
      });
    })

  },
  submitOrder() {
    app.http(API.apiSubmitOrder, {
      car_info_save_source: 1,
      userId: this.data.userId,
      bind_tel: this.data.etcInfo.saveAccountInfoRequest.mobilephone,
      address: this.data.etcInfo.saveCarInfoRequest.vehicle_info_address,
      accountId: this.data.etcInfo.accountId,
      carInfoId: this.data.etcInfo.carInfoId,
      userno: this.data.etcInfo.userno,
      recharege_flag: '02',
      whether_mail: '01',
      price: 0,
      product_id: '02',
      user_type: 8,
      spe_flag: '1',
      issue_date: this.data.etcInfo.saveCarInfoRequest.issue_date,
      register_date: this.data.etcInfo.saveCarInfoRequest.register_date,
      idtype: this.data.etcInfo.saveAccountInfoRequest.idtype,
      idnum: this.data.etcInfo.saveAccountInfoRequest.idnum,
      organ: this.data.etcInfo.saveAccountInfoRequest.organ,
      owner: this.data.etcInfo.saveCarInfoRequest.owner,
      vehicle_plate: this.data.etcInfo.saveCarInfoRequest.vehicle_plate,
      vehicle_color: this.data.etcInfo.saveCarInfoRequest.vehicle_color,
      vehicle_type: 0,
      vehicle_axles: this.data.etcInfo.saveCarInfoRequest.vehicle_axles,
      vehicle_wheels: this.data.etcInfo.saveCarInfoRequest.vehicle_wheels,
      vehicle_txtclass: this.data.etcInfo.saveCarInfoRequest.vehicle_txtclass,
      func_type: this.data.etcInfo.saveCarInfoRequest.func_type,
      factory_code: this.data.etcInfo.saveCarInfoRequest.factory_code,
      engine_code: this.data.etcInfo.saveCarInfoRequest.engine_code,
      vehicle_code: this.data.etcInfo.saveCarInfoRequest.vehicle_code,
      vehicle_length: this.data.etcInfo.saveCarInfoRequest.vehicle_length,
      vehicle_width: this.data.etcInfo.saveCarInfoRequest.vehicle_width,
      vehicle_height: this.data.etcInfo.saveCarInfoRequest.vehicle_height,
      veh_license_pic_url1: this.data.etcInfo.saveCarInfoRequest.veh_license_pic_url1,
      veh_license_pic_url2: this.data.etcInfo.saveCarInfoRequest.veh_license_pic_url2,
      total_mass: this.data.etcInfo.saveCarInfoRequest.total_mass,
      maintenance_mass: this.data.etcInfo.saveCarInfoRequest.maintenance_mass,
      permitted_tow_weight: this.data.etcInfo.saveCarInfoRequest.permitted_tow_weight,
      vehicle_capacity: '',
      approved_count: this.data.etcInfo.saveCarInfoRequest.approved_count,
      owner_picurl1: this.data.etcInfo.saveCarInfoRequest.owner_picurl1 || '',
      owner_picurl2: this.data.etcInfo.saveCarInfoRequest.owner_picurl2 || '',
      owner_id_type: this.data.etcInfo.saveCarInfoRequest.owner_id_type || '',
    }).then(res => {
      if (res.code == 200) {
        wx.navigateTo({
          url: '/pages/biddingBank/biddingBank?etcInfo=' + JSON.stringify(etcInfo)
        });
      } else {
        wx.showModal({
          title: '提示',
          content: res.message,
          confirmColor: '#005866',
          showCancel: false,
          success(res) {}
        })
        wx.hideLoading();
      }
    }).catch(err => {
      console.log(err, 'submitBusiness')
      wx.showToast({
        title: '请求超时',
        icon: 'none',
        duration: 3000,
        mask: false
      });
    })

  },
  toOrder() {
    if (!this.data.userId) {
      this.setData({
        isLogin: true,
        isMask: true,
      })
      return;
    }
    wx.navigateTo({
      url: '/pages/orderList/orderList'
    })
  },
  cancelCode() {
    this.setData({
      isShowanimation: true,
      isShowCode: false,
      isMask: false,
    })

  },
  cancelCode2() {
    this.setData({
      customerserviceshow: false,
      isMask: false,
    })
  },
  onShow() {
    wx.checkSession({
      success: () => {
        let userId = wx.getStorageSync('userId') || '';
        if (userId == '') {
          this.setData({
            isAuthorizeGetUserInfo: false,
            userId
          })
        } else {
          this.setData({
            isAuthorizeGetUserInfo: true,
            userId
          })
        }
      },
      fail: () => {
        this.setData({
          isAuthorizeGetUserInfo: true,
          userId: ''
        })
      }
    })
    app.http(API.apiQueryList, {
      cmsContentCategoryId: 1,
      pageNum: 1,
      pageSize: 10,
    }, {
      method: 'get'
    }, 'application/json', true).then(res => {
      if (res.code == 200) {
        this.setData({
          swiperInfo: res.data.list
        })
      }

    })
    if (!this.data.indexVideo) {
      app.http(API.apiQueryList, {
        cmsContentCategoryId: 0,
        pageNum: 1,
        pageSize: 10,
      }, {
        method: 'get'
      }, 'application/json', true).then(res => {
        if (res.code == 200) {
          this.setData({
            indexVideo: res.data.list[0].icon
          })
        }

      })
    }

  },
  showLogin() {
    this.setData({
      isLogin: true,
      isMask: true
    })
  },
  closeLogin() {
    this.setData({
      isLogin: false,
      isMask: false
    })
  },
  previewImage() {
    this.setData({
      customerserviceshow: true,
      isMask: true,
    })
    // wx.previewImage({
    //     current: 'https://yxyt.oss-cn-hangzhou.aliyuncs.com/ghac/eqr.png', // 当前显示图片的 http 链接
    //     urls: ['https://yxyt.oss-cn-hangzhou.aliyuncs.com/ghac/eqr.png'] // 需要预览的图片 http 链接列表
    // })
  },
  goCustomer() {
    wx.openCustomerServiceChat({
      extInfo: {
        url: 'https://work.weixin.qq.com/kfid/kfc245b4ba5186c3885'
      },
      corpId: 'wwb6e5327272e3bc4e',
      success(res) {}
    })
  },
  // 授权登录
  getPhoneNumber(e) {
    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      app.login({
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv,
        carBrand: 0,
        code: this.data.code
      }).then(response => {
        console.log(this.data.applylist);
        if (!this.data.userId && this.data.applylist == '') {
          this.setData({
            isShowanimation: false,
            isLogin: false,
            isMask: true,
            isShowCode: true,
            userId: response.userId,
          })
        }
        if (!this.data.userId && !this.data.applylist) {
          this.setData({
            isMask: false,
            isShowCode: false,
            isLogin: false,
            isShowanimation: false,
            userId: response.userId,
          })
        }

        // let optSync = wx.getLaunchOptionsSync()
        // if (optSync.scene == '1011' || optSync.scene == "1012" || optSync.scene == '1013' || optSync.scene == '1065' || optSync.scene == '1167' || optSync.scene == '1168' || optSync.scene == '1169' || optSync.scene == '1181' || optSync.scene == '1194') {

        // } else {
        // this.setData({
        //     userId: response.userId,
        //     isLogin: false,
        //     isMask: false,
        // })
        // }
      }).catch(err => {
        this.getCode()
      })

    }

  },
  getUserLocation() {
    wx.getSetting({
      success: (res) => {
        console.log(res);
        // console.log(JSON.stringify(res))
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      //this.getLocation();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          //this.getLocation();
        } else {
          //调用wx.getLocation的API
          //this.getLocation();
        }
      }
    })
  },
  // 微信获得经纬度
  getLocation() {
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        // console.log(JSON.stringify(res))
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy;
        // console.log(latitude);
        // this.getLocal(latitude, longitude)
      },
      fail: (res) => {
        console.log('fail' + JSON.stringify(res))
      }
    })
  },
  // 获取当前地理位置
  getLocal(x, y) {
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: x,
        longitude: y
      },
      success: (res) => {
        console.log(res);
        this.setData({
          nation: res.result.address_component.nation,
          province: res.result.address_component.province,
          city: res.result.address_component.city,
          district: res.result.address_component.district,
          address: res.result.address,
        })
        // console.log(JSON.stringify(res));
        let province = res.result.ad_info.province
        // console.log(province, x, y);
        let city = res.result.ad_info.city
        this.setData({
          province: province,
          city: city,
          latitude: x,
          longitude: y
        })
        this.getposition()

      },
      fail: (res) => {
        console.log(res);
      },
      complete: (res) => {
        // console.log(res);
      }
    });

  },
  getposition() {
    const data = {
      // 在这里设置请求参数
      nation: this.data.nation,
      province: this.data.province,
      city: this.data.city,
      district: this.data.district,
      address: this.data.address
    };
    wx.request({
      url: 'https://gac.yxytcar.cn/v1/api/ue/order/etcUserLoaction',
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      data: JSON.stringify(data),
      success: function (res) {
        if (res.code == 200) {
          console.log(res);
        }
      },
      fail: function (error) {
        console.error(error);
      }
    });

  },
  openPrivacyContract() {
    wx.openPrivacyContract({
      success: res => {
        console.log('openPrivacyContract success', res)
      },
      fail: res => {
        console.error('openPrivacyContract fail', res)
      }
    })
  },
})